package com.example.musicaiap.ui.library

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Album
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.foundation.layout.WindowInsets // Ensure WindowInsets is imported
import androidx.compose.foundation.layout.statusBars // Ensure statusBars is imported (though not directly used here, TopAppBarDefaults uses it)
// Removed windowInsetsPadding import as it's no longer used on TopAppBar modifier
import androidx.compose.material3.TopAppBarDefaults // Ensure TopAppBarDefaults is imported
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color // Ensure Color is imported
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.media3.common.util.UnstableApi // Keep if needed by other parts
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.R // Import R for drawable resources
import com.example.musicaiap.domain.model.Song // Import Song model
import com.example.musicaiap.ui.theme.MusicAIAPTheme // Ensure this import exists
import com.example.musicaiap.ui.theme.RedAccent // Import RedAccent

@OptIn(ExperimentalMaterial3Api::class)
@Composable
@UnstableApi // Keep if needed
fun LibraryScreen(
    modifier: Modifier = Modifier,
    localSongs: List<Song>, // Add parameter for song list
    onSongClick: (Song) -> Unit, // Add parameter for song click
    onMoreClick: (Song) -> Unit, // Add parameter for more options click
    onPlaylistCategoryClick: () -> Unit, // Callback for Playlist category
    onAlbumCategoryClick: () -> Unit, // Callback for Album category
    onArtistCategoryClick: () -> Unit, // Callback for Artist category
    onFolderCategoryClick: () -> Unit, // Callback for Folder category
    onSearchClick: () -> Unit, // Callback for Search icon
    onMoreOptionsClick: () -> Unit // Callback for More options icon
) {
    Scaffold(
        modifier = modifier.fillMaxSize(),
        containerColor = Color.Transparent, // Explicitly set Scaffold background to transparent
        topBar = {
            TopAppBar(
                windowInsets = TopAppBarDefaults.windowInsets, // Use M3 insets handling
                title = { Text("媒体库") },
                actions = {
                    IconButton(onClick = onSearchClick) { // Use callback
                        Icon(Icons.Filled.Search, contentDescription = "搜索")
                    }
                    IconButton(onClick = onMoreOptionsClick) { // Use callback
                        Icon(Icons.Filled.MoreVert, contentDescription = "更多选项")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent, // Make TopAppBar transparent
                    titleContentColor = MaterialTheme.colorScheme.onSurface, // Adjust if needed for contrast
                    actionIconContentColor = MaterialTheme.colorScheme.onSurfaceVariant // Adjust if needed for contrast
                )
            )
        }
    ) { paddingValues ->
        // Apply fillMaxSize first, then padding
        Column(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
            // Category Items Card
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp), // Add padding around the card
                shape = RoundedCornerShape(12.dp), // Apply rounded corners
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surface // White background
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) // Subtle elevation
            ) {
                Column {
                    CategoryItem(
                        icon = Icons.Filled.Menu,
                        iconTint = RedAccent,
                        text = "播放列表",
                        onClick = onPlaylistCategoryClick // Use callback
                    )
                    CategoryItem(
                        icon = Icons.Filled.Album,
                        iconTint = RedAccent,
                        text = "专辑",
                        onClick = onAlbumCategoryClick // Use callback
                    )
                    CategoryItem(
                        icon = Icons.Filled.Mic,
                        iconTint = RedAccent,
                        text = "歌手",
                        onClick = onArtistCategoryClick // Use callback
                    )
                    CategoryItem(
                        icon = Icons.Filled.Folder,
                        iconTint = RedAccent,
                        text = "文件夹",
                        onClick = onFolderCategoryClick, // Use callback
                        showDivider = false // No divider after the last item
                    )
                }
            }

            Spacer(modifier = Modifier.height(8.dp)) // Adjust spacing

            // Local Song List
            LazyColumn(
                modifier = Modifier.weight(1f), // Allow list to take remaining space
                contentPadding = PaddingValues(bottom = 8.dp) // Add padding at the bottom
            ) {
                // Optional: Add a header for the song list if needed
                // item {
                //     Text(
                //         text = "本地歌曲 (${localSongs.size})",
                //         style = MaterialTheme.typography.titleMedium,
                //         modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
                //     )
                // }

                items(localSongs, key = { it.id }) { song ->
                    LocalSongListItem(
                        song = song,
                        onClick = { onSongClick(song) }, // Pass song to callback
                        onMoreClick = { onMoreClick(song) } // Pass song to callback
                    )
                    // Add divider between songs
                    Divider(
                        modifier = Modifier.padding(start = 76.dp), // Align with text start after icon+spacer
                        thickness = 0.5.dp,
                        color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f)
                    )
                }
            }
        }
    }
}

/**
 * 可复用的分类列表项 Composable
 */
@Composable
private fun CategoryItem(
    icon: ImageVector,
    iconTint: Color,
    text: String,
    onClick: () -> Unit,
    showDivider: Boolean = true
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .padding(horizontal = 16.dp, vertical = 12.dp), // 调整垂直内边距
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween // 使箭头靠右
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    imageVector = icon,
                    contentDescription = text,
                    tint = iconTint,
                    modifier = Modifier.size(24.dp) // 标准图标大小
                )
                Spacer(modifier = Modifier.width(16.dp)) // 图标和文字间距
                Text(
                    text = text,
                    style = MaterialTheme.typography.bodyLarge, // 使用合适的文本样式
                    fontSize = 16.sp // 明确字体大小
                )
            }
            Icon(
                imageVector = Icons.Filled.ChevronRight,
                contentDescription = "进入",
                tint = MaterialTheme.colorScheme.onSurfaceVariant // 箭头颜色
            )
        }
        if (showDivider) {
            Divider(
                modifier = Modifier.padding(start = 56.dp), // 左侧缩进以对齐文本 (图标大小 + 间距)
                thickness = 0.5.dp,
                color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) // 分割线颜色
            )
        }
    }
}

/**
 * 本地音乐列表项 Composable (新样式)
 */
@Composable
fun LocalSongListItem(
    song: Song,
    onClick: () -> Unit,
    onMoreClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 圆形封面或占位符
        Box(
            modifier = Modifier
                .size(48.dp) // 调整大小以匹配图片
                .clip(CircleShape) // 圆形裁剪
                .background(MaterialTheme.colorScheme.surfaceVariant), // 占位符背景色
            contentAlignment = Alignment.Center
        ) {
            // 尝试加载封面，如果失败或为空则显示默认图标
            AsyncImage(
                model = ImageRequest.Builder(LocalContext.current)
                    .data(song.coverUrl.ifEmpty { null }) // 如果URL为空则不加载
                    .error(R.drawable.ic_notification_music) // 加载失败时显示默认图标
                    .placeholder(R.drawable.ic_notification_music) // 占位符
                    .crossfade(true)
                    .build(),
                contentDescription = "歌曲封面",
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
                // Removed onError and fallback parameters
                /* onError = { Error handled by .error() }, */
                /* fallback = { // 当 model 为 null 时显示
                    Icon(
                        imageVector = Icons.Filled.MusicNote, */
                        // Removed stray contentDescription = null line
                        /* tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(24.dp)
                    )
                } */
            )
        }

        Spacer(modifier = Modifier.width(16.dp))

        // 歌曲标题和艺术家
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = song.title,
                style = MaterialTheme.typography.bodyLarge,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                color = MaterialTheme.colorScheme.onSurface // 主要文本颜色
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = song.artist.takeIf { it.isNotEmpty() } ?: "未知艺术家", // 显示"未知艺术家"如果为空
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant, // 次要文本颜色
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }

        Spacer(modifier = Modifier.width(8.dp))

        // 更多选项按钮
        IconButton(onClick = onMoreClick) {
            Icon(
                imageVector = Icons.Filled.MoreVert,
                contentDescription = "更多选项",
                tint = MaterialTheme.colorScheme.onSurfaceVariant // 图标颜色
            )
        }
    }
}


@Preview(showBackground = true)
@Composable
fun LibraryScreenPreview() {
    val sampleSongs = List(10) { index ->
        Song(
            id = index.toString(),
            title = "歌曲标题 $index",
            artist = if (index % 3 == 0) "" else "艺术家 $index",
            album = "专辑 $index",
            url = "",
            coverUrl = if (index % 4 == 0) "" else "https://via.placeholder.com/150", // Some with covers, some without
            duration = (180 + index * 10) * 1000L
            // Removed isLocal and isFavorite from preview Song creation
        )
    }
    MusicAIAPTheme {
        LibraryScreen(
            localSongs = sampleSongs,
            onSongClick = {},
            onMoreClick = {},
            onPlaylistCategoryClick = {},
            onAlbumCategoryClick = {},
            onArtistCategoryClick = {},
            onFolderCategoryClick = {},
            onSearchClick = {},
            onMoreOptionsClick = {}
        )
    }
}

// 添加 CategoryItem 的预览
@Preview(showBackground = true)
@Composable
fun CategoryItemPreview() {
    MusicAIAPTheme {
        Column {
            CategoryItem(
                icon = Icons.Filled.Menu,
                iconTint = RedAccent, // Use RedAccent
                text = "播放列表",
                onClick = {}
            )
            CategoryItem(
                icon = Icons.Filled.Album,
                iconTint = RedAccent, // Use RedAccent
                text = "专辑",
                onClick = {},
                showDivider = false
            )
        }
    }
}

// 添加 LocalSongListItem 的预览
@Preview(showBackground = true)
@Composable
fun LocalSongListItemPreview() {
    val sampleSong = Song(
        id = "1",
        title = "迷人的梦想 - aac",
        artist = "未知",
        album = "未知专辑",
        url = "", // 留空以测试占位符
        coverUrl = "", // 留空以测试占位符
        duration = 240000
        // Removed isLocal and isFavorite from preview Song creation
    )
    MusicAIAPTheme {
        Column {
            LocalSongListItem(song = sampleSong, onClick = {}, onMoreClick = {})
            LocalSongListItem(
                song = sampleSong.copy(id = "2", title = "歌曲标题过长就会省略掉显示效果看看怎么样", artist = "一个名字很长的艺术家"),
                onClick = {},
                onMoreClick = {}
            )
            LocalSongListItem(
                song = sampleSong.copy(id = "3", coverUrl = "https://via.placeholder.com/150"), // With cover
                // Removed isLocal and isFavorite from preview Song creation
                onClick = {},
                onMoreClick = {}
            )
        }
    }
}
